#include "easylogging++.h"
#include "kcpserver.h"
#include "Util.h"

void KCPServer::SendData(string ip, string port, shared_ptr<std::vector<unsigned char> > data) {
	LOG(INFO) << "Send" << ip << port << data;
	auto udpPort = ip+port;
	//客户端还未连接服务器 或者客户端已经断开了？
	if(agents.find(udpPort) == agents.end()) {
		LOG(INFO) << "ClientNot:" << udpPort;
	}else {
		auto agent = agents[udpPort];
		agent->SendData(data);
	}
}

void KCPServer::OnReceiveUDP(string ip, string port, shared_ptr<std::vector<unsigned char> > data){
	LOG(INFO) << ip << port << data;
	auto udpPort = ip+port;
	if(agents.find(udpPort) == agents.end()) {
		auto agent = shared_ptr<KCPAgent>(new KCPAgent(udpPort, this));
		AddAgent(agent);
	}
	auto agent1 = agents[udpPort];
	agent1->ReceiveData(data);
}

void KCPServer::AddAgent(shared_ptr<KCPAgent> agent){
	agents.insert(std::make_pair(agent->remoteEnd, agent));
}

void KCPServer::Update() {
	auto now = GetNow();
	auto delta = now-lastTime;
	lastTime = now;
	for(auto it = agents.begin(); it != agents.end(); it++) {
		it->second->Update(delta);
	}

	for(auto it = closedAgents.begin(); it != closedAgents.end(); it++) {
		agents.erase((*it)->remoteEnd);
	}
}

//作为Update的返回值给传给Erlang
//KCP--->UDP层
void KCPServer::SendUDPPacket(shared_ptr<KCPPacket> pa) {
	LOG(INFO) << "SendUDPPacket:";
	sendUDPPackets.push_back(pa);
}

//KCP--->业务层
void KCPServer::ReceiveKCPPacket(shared_ptr<KCPPacket> packet) {
	LOG(INFO) << "ReceiveKCPPacket";
	receiveKcpPackets.push_back(packet);
}

void KCPServer::RemoveAgent(KCPAgent *agent) {
	auto re = agent->remoteEnd;
	LOG(INFO)<<"RemoveAgent";
	if(agents.find(re) != agents.end()) {
		auto ag = agents[re];
		//agents.erase(re);
		closedAgents.push_back(ag);
	}
}

//业务层直接删除 不能再Update中执行
void KCPServer::CloseAgent(string udpPort) {
	if(agents.find(udpPort) != agents.end()) {
		LOG(INFO) << "CloseAgent:" << udpPort;
		auto ag = agents[udpPort];
		agents.erase(udpPort);
		ag->Close();	
	}
}